﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using CommonUtils;
using System.Security;
using System.Text.RegularExpressions;

namespace ShellAnywhere.Model
{

	public enum TargetDirectoryType
	{
		Dir,
		Env
	}
	[XmlRoot]
	public class TargetDirectories
	{
		public TargetDirectories(string[] paths, TargetDirectoryType type)
		{
			Paths = paths;
			Type = Type;
		}
		[XmlAttribute]
		public string[] Paths { get; set; }
		[XmlAttribute]
		public TargetDirectoryType Type { get; set;}

		public List<ITarget> Load()
		{
			List<ITarget> targets = new List<ITarget>();

			switch (Type)
			{
				case TargetDirectoryType.Dir:
					targets.AddRange(LoadDir(Paths));
					break;
				case TargetDirectoryType.Env:
					targets.AddRange(LoadEnv(Paths));
					break;
			}

			return targets;
		}
		private List<ITarget> LoadDir(string[] directories)
		{
			List<ITarget> targets = new List<ITarget>();

			foreach (string directory in directories)
			{
				if (Directory.Exists(directory))
				{
					string[] files = Common.FindFiles(directory, SearchOption.TopDirectoryOnly, true, "*.exe");
					foreach (string file in files)
						targets.Add(new Target(file));
				}
			}

			return targets;
		}
		private List<ITarget> LoadEnv(string[] environmentVariables)
		{
			List<string> directories = new List<string>();
			try
			{
				foreach (string env in environmentVariables)
				{
					string value = Environment.GetEnvironmentVariable(env);
					string[] values = Regex.Split(value, ";");
					if (values != null && values.Length > 0)
						directories.AddRange(values);
				}
			}
			catch (ArgumentNullException anex)
			{
				Console.WriteLine("anex: " + anex.Message);
			}
			catch (SecurityException sex)
			{
				Console.WriteLine("sex: " + sex.Message);
			}
			return LoadDir(directories.ToArray());
		}
	}

	[XmlRoot]
	public class TargetsAndDirectories
	{
		public TargetsAndDirectories(List<TargetDirectories> directories, List<Target> targets)
		{
			Directories = directories;
			Targets = targets;
		}

		[XmlArray]
		public List<TargetDirectories> Directories { get; set; }

		[XmlArray]
		public List<Target> Targets { get; set; }
	}
}
